# encoding: utf-8
class ApplicationController < ActionController::Base
	protect_from_forgery
	
	# ucitavanje podataka za sidebar
	def load_sidebar
		groups = "LEFT JOIN groups on group_id = groups.id"
		permissions = "LEFT JOIN permissions on permission_id = permissions.id"
		
		if current_member.nil?
			my_permission = 4
		else
			my_permission = current_member.permission_id		
		end
		
		@feeds = Feed.joins(groups).joins(permissions).where("permission_id > ?",my_permission).order("created_at DESC").limit(8)
	end
	
	# sprijecava ispis noindex HTML taga
	def do_index
		@doindex = true
	end

	# u slucaju da korisnik nije prijavljen, ili je banan, redirecta na login
	def require_login
		if current_member == nil
			redirect_to new_member_session_path
		return false
		else
			if current_member.permission.id == 6
				redirect_to new_member_session_path
			return false
			end
		end

		return true
	end

	# provjeri jeli korisnik odobren, tj jeli mu razina dopustenja odobreni clan
	def require_approved_member

		if current_member == nil
			redirect_to new_member_session_path
		return false
		else
			unless current_member.is_approved?
				redirect_to root_url
			return false
			end
		end

		return true

	end

	# provjeri jeli korisnik prijavljen i moderator, ako nije redirectaj na pocetnu stranu
	def require_moderator
		if current_member == nil
			redirect_to new_member_session_path
			return false
		else
			unless current_member.is_moderator?
				redirect_to root_url
				return false
			end
		end
		return true
	end

	# provjeri jeli korisnik prijavljen i administrator, ako nije redirectaj na pocetnu stranu
	def require_admin
		if current_member == nil
			redirect_to new_member_session_path
			return false
		else
			if current_member.permission.id != 1
				redirect_to root_url
				return false
			end
		end
		return true
	end

	# provjeri ima li korisnik potrebne dozvole (ovisno o grupi)
	def require_group_permission(group)

		if group.permission.id == 1
			return require_admin
		end

		if group.permission.id == 2
			return require_moderator
		end

		if group.permission.id == 3
			return require_approved_member
		end

		if group.permission.id == 4
			return require_login
		end

		return true

	end

	# provjerava jeli korisnik admin ili navedeni clan (korisno kod editiranja postova i slicno)
	def require_moderator_or_this_member(member)
		unless current_member.is_moderator_or_this_member? member
			redirect_to root_url
		return false
		end

		return true
	end
	
	# provjerava jeli korisnik admin ili navedeni clan (korisno kod editiranja postova i slicno)
	def require_admin_or_this_member(member)
		unless current_member.is_admin_or_this_member? member
			redirect_to root_url
		return false
		end

		return true
	end

end
